<template>
  <div class="exam-platform">
    <!-- Header -->
  <NavBar @toggle-sidebar="toggleSidebar" />
    <main class="main-content">
      <div class="content-header">
        <div class="header-left">
          <h2 class="page-title">可用考试</h2>
          <p class="page-subtitle">从已经发布的考试中进行选择</p>
        </div>        <div class="header-right">
          <!-- 班级搜索框 -->
          <div class="search-input-container">
            <input 
              ref="searchInput"
              v-model="searchQuery" 
              @input="handleSearchInput"
              @focus="showClassDropdown = true"
              @blur="hideDropdown"
              type="text" 
              :placeholder="selectedClassName ? `已选择: ${selectedClassName}` : '搜索班级名称'"
              class="search-input"
            />
            <button @click="clearFilter" class="clear-btn" v-if="selectedClassName">×</button>
            
            <!-- 班级下拉列表 -->
            <div v-if="showClassDropdown && filteredClassList.length > 0" class="class-dropdown">
              <div 
                v-for="cls in filteredClassList" 
                :key="cls.classId"
                @mousedown="selectClass(cls)"
                class="dropdown-item"
              >
                {{ cls.name }}
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- Exam Cards Container -->
      <div class="exam-cards-container">
        <!-- Loading State -->
        <div v-if="loading" class="loading-container">
          <div class="loading-spinner"></div>
          <p class="loading-text">正在加载考试数据...</p>
        </div>

        <!-- Error State -->
        <div v-else-if="error" class="error-container">
          <p class="error-text">{{ error }}</p>
          <button class="retry-btn" @click="loadExamData">重新加载</button>
        </div>        <!-- Empty State -->
        <div v-else-if="filteredExamList.length === 0" class="empty-container">
          <p class="empty-text">{{ selectedClassName ? `${selectedClassName} 班级暂无可用考试` : '暂无可用考试' }}</p>
        </div>

        <!-- Exam Cards -->
        <div
            v-else
            v-for="exam in filteredExamList"
            :key="exam.examId"
            class="exam-card"
        >
          <div class="exam-header">
            <div class="exam-left-info">
              <div class="exam-meta-item">
                <div class="meta-label">考试编号</div>
                <div class="meta-badge">{{ exam.examNumber }}</div>
              </div>
              <div class="exam-meta-item">
                <div class="meta-label">发布人</div>
                <div class="meta-badge">{{ exam.publisher }}</div>
              </div>
            </div>
            <div class="exam-right-info">
              <div class="exam-title-section">
                <h3 class="exam-title">{{ exam.title }}</h3>
                <div class="status-indicator"></div>
              </div>
            </div>
          </div>

          <div class="exam-body">
            <div class="exam-details">
              <span class="details-label">详情：</span>
              <span class="details-text">{{ exam.description }}</span>
            </div>
            <div class="exam-time-info">
              <div class="exam-time">{{ exam.timeRange }}</div>
              <div class="exam-duration">{{ exam.duration }}</div>
            </div>
          </div>

          <div class="exam-actions">
            <button class="action-btn materials-btn" @click="viewMaterials(exam.examId)">
              考试资料
            </button>
            <button class="action-btn start-btn" @click="startExam(exam.examId)">
              开始考试
            </button>
          </div>
        </div>
      </div>

      <!-- Footer Section -->
      <div class="footer-section">
        <div style="flex:1"></div>
        <!-- <button class="refresh-btn" @click="refreshExamData" :disabled="loading">
          {{ loading ? '加载中...' : '刷新' }}
        </button> -->
        <div class="footer-note">
          考试时间以系统时间为准，请提前做好准备
        </div>
      </div>
    </main>
  </div>
</template>

<script setup>
import { ref, onMounted, computed, nextTick } from 'vue'
import { useRouter } from 'vue-router'
// 注意：请确保已正确配置API路径
import { getAllAvailableExamsAPI } from '../apis/examAPI/StudentExamsAPI'
import { getAllClassesAPI, getClassByIdAPI } from '../apis/classmanageAPI/classesAPI'
import NavBar from "@/components/NavBar.vue";

const router = useRouter()

// 获取当前学生ID
const studentId = Number(localStorage.getItem('id')) // 默认值123作为fallback

// 考试列表数据 - 使用真实的API数据结构
const examList = ref([])
const loading = ref(true)
const error = ref('')

// 班级数据
const classList = ref([])
const classMap = ref(new Map()) // 用于存储 classId -> className 的映射

// 搜索相关状态
const selectedClassName = ref('')
const searchQuery = ref('')
const searchInput = ref(null)
const showClassDropdown = ref(false)

// 过滤后的考试列表 - 基于班级名称筛选
const filteredExamList = computed(() => {
  if (!selectedClassName.value) {
    return examList.value
  }
  // 根据选中的班级名称找到对应的classId
  const selectedClassId = Array.from(classMap.value.entries())
    .find(([id, name]) => name === selectedClassName.value)?.[0]
  
  if (!selectedClassId) {
    return examList.value
  }
  
  return examList.value.filter(exam => exam.classId === selectedClassId)
})

// 过滤后的班级列表 - 用于下拉框搜索
const filteredClassList = computed(() => {
  if (!searchQuery.value) {
    return classList.value
  }
  const searchTerm = searchQuery.value.toLowerCase()
  return classList.value.filter(cls => 
    cls.name.toLowerCase().includes(searchTerm)
  )
})

// 页面跳转方法
const goToResource = (examId) => {
  router.push({
    path: '/student-exam-resource',
    query: { examId: examId }
  })
}

const goToRealize = (examId) => {
  router.push({
    path: '/student-exam-realize',
    query: { examId: examId }
  })
}

// 方法定义
const viewMaterials = (examId) => {
  console.log('查看考试资料:', examId)
  goToResource(examId)
}

const startExam = (examId) => {
  console.log('开始考试:', examId)
  goToRealize(examId)
}

// 格式化时间范围
const formatTimeRange = (startTime, endTime) => {
  if (!startTime || !endTime) return '时间待定'
  const start = new Date(startTime).toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit'
  }).replace(/\//g, '/').replace(/,/g, '')
  const end = new Date(endTime).toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit'
  }).replace(/\//g, '/').replace(/,/g, '')
  return `${start}-${end}`
}

// 格式化持续时间
const formatDuration = (duration) => {
  if (!duration) return '时长待定'
  return `${duration}分钟`
}

// 获取班级数据
const loadClassData = async () => {
  try {
    const res = await getAllClassesAPI()
    if (res.code === 200 && Array.isArray(res.data)) {
      classList.value = res.data
      // 创建 classId -> className 映射
      classMap.value.clear()
      res.data.forEach(cls => {
        classMap.value.set(cls.classId, cls.name)
      })
    } else {
      console.error('获取班级数据失败:', res.message)
    }
  } catch (err) {
    console.error('获取班级数据出错:', err)
  }
}

// 获取真实考试数据
const loadExamData = async () => {
  try {    loading.value = true
    error.value = ''

    // 确保班级数据已加载
    if (classList.value.length === 0) {
      await loadClassData()
    }

    // 使用动态获取的学生ID
    const res = await getAllAvailableExamsAPI(studentId)

    if (res.code === 200 && Array.isArray(res.data)) {      // 将API数据转换为组件需要的格式
      examList.value = res.data.map(exam => ({
        id: exam.examId,
        examNumber: exam.examId.toString(),
        publisher: `${exam.teacherId}`, // 可以后续通过API获取教师真实姓名
        title: exam.title,
        description: exam.description,
        timeRange: formatTimeRange(exam.startTime, exam.endTime),
        duration: formatDuration(exam.duration),
        examId: exam.examId,
        teacherId: exam.teacherId,
        classId: exam.classId, // 添加classId字段
        className: classMap.value.get(exam.classId) || '未知班级', // 添加班级名称
        status: exam.status || 'active'
      }))
    } else {
      console.error('获取考试数据失败:', res.message)
      error.value = res.message || '获取考试数据失败'
      examList.value = []
    }
  } catch (err) {
    console.error('获取考试数据出错:', err)
    error.value = '网络错误，请检查网络连接后重试'
    examList.value = []
  } finally {
    loading.value = false
  }
}

// 组件挂载时加载数据
onMounted(async () => {
  await loadClassData() // 先加载班级数据
  await loadExamData()  // 再加载考试数据
})

// 刷新数据方法
const refreshExamData = () => {
  loadExamData()
}

// 搜索相关方法
const handleSearchInput = () => {
  showClassDropdown.value = true
}

const hideDropdown = () => {
  setTimeout(() => {
    showClassDropdown.value = false
  }, 200)
}

const selectClass = (cls) => {
  selectedClassName.value = cls.name
  searchQuery.value = cls.name
  showClassDropdown.value = false
}

const clearFilter = () => {
  selectedClassName.value = ''
  searchQuery.value = ''
  showClassDropdown.value = false
}
</script>

<style scoped>
/* 全局重置 */
* {
  box-sizing: border-box;
}

/*
  注意：如果组件还没有完全铺满屏幕，请确保在您的全局CSS中添加：
  body, html {
    margin: 0;
    padding: 0;
  }
*/

.exam-platform {
  width: 100vw;
  min-height: 100vh;
  position: relative;
  background: linear-gradient(90deg, #E2E8F0 0%, #F1F5F9 47%, #F8FAFC 100%);
  font-family: 'Inter', sans-serif;
}

/* Header */
.header {
  width: 100%;
  height: 73px;
  background: white;
  border-bottom: 0.67px solid #D9D9D9;
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0 24px;
  box-sizing: border-box;
}

.logo {
  display: flex;
  align-items: center;
  gap: 16px;
}

.logo-icon {
  width: 40px;
  height: 40px;
  background: #2C2C2C;
  border-radius: 8px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.logo-symbol {
  width: 19.2px;
  height: 19.2px;
  background: white;
  border-radius: 2px;
}

.platform-title {
  color: #1E1E1E;
  font-size: 24px;
  font-weight: 700;
  line-height: 36px;
  margin: 0;
}

.navigation {
  display: flex;
  gap: 64px;
}

.nav-item {
  color: #B3B3B3;
  font-size: 16px;
  font-weight: 400;
  line-height: 24px;
  text-decoration: none;
  position: relative;
  transition: color 0.2s;
}

.nav-item.active {
  color: #2C2C2C;
  font-weight: 500;
}

.nav-item.active::after {
  content: '';
  position: absolute;
  bottom: -25px;
  left: 0;
  width: 100%;
  height: 2px;
  background: #2C2C2C;
}

.nav-item:hover {
  color: #2C2C2C;
}

/* Main Content */
.main-content {
  padding: 20px 32px;
  margin: 0 auto;
  width: 100%;
  box-sizing: border-box;
}

.content-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 48px;
  position: relative;
}

.header-left {
  flex: 1;
}

.header-right {
  position: relative;
  z-index: 10;
}

.page-title {
  color: #1E1E1E;
  font-size: 40px;
  font-weight: 700;
  line-height: 72px;
  margin: 0 0 16px 0;
  text-align: left;
}

.page-subtitle {
  color: #B3B3B3;
  font-size: 18px;
  font-weight: 400;
  line-height: 30px;
  margin: -8px 0 0 0;
  text-align: left;
}

/* 搜索输入框样式 */
.search-input-container {
  position: relative;
  background: white;
  border: 1px solid #D9D9D9;
  border-radius: 9999px;
  padding: 12px 16px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  display: flex;
  align-items: center;
  gap: 8px;
  min-width: 280px;
  transition: all 0.2s;
}

.search-input-container:hover {
  border-color: #2C2C2C;
}

.search-input-container:focus-within {
  border-color: #2C2C2C;
  box-shadow: 0 2px 12px rgba(44, 44, 44, 0.2);
}

.search-input {
  flex: 1;
  border: none;
  outline: none;
  font-size: 16px;
  font-family: Inter;
  color: #1E1E1E;
  background: transparent;
}

.search-input::placeholder {
  color: #B3B3B3;
}

.clear-btn {
  background: #f0f0f0;
  border: none;
  border-radius: 50%;
  width: 20px;
  height: 20px;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  color: #666;
  font-size: 14px;
  transition: background-color 0.2s;
}

.clear-btn:hover {
  background: #e0e0e0;
}

/* 班级下拉列表样式 */
.class-dropdown {
  position: absolute;
  top: calc(100% + 4px);
  left: 0;
  right: 0;
  background: white;
  border: 1px solid #D9D9D9;
  border-radius: 8px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
  max-height: 200px;
  overflow-y: auto;
  z-index: 1000;
}

.dropdown-item {
  padding: 10px 16px;
  cursor: pointer;
  font-size: 14px;
  color: #1E1E1E;
  border-bottom: 1px solid #f5f5f5;
  transition: background-color 0.2s;
}

.dropdown-item:last-child {
  border-bottom: none;
}

.dropdown-item:hover {
  background-color: #f8f9fa;
}

.dropdown-item:active {
  background-color: #e9ecef;
}

/* Footer Section */
.footer-section {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 16px;
  margin-top: 48px;
  padding: 24px;
}

.refresh-btn {
  background: #2C2C2C;
  color: white;
  border: none;
  border-radius: 6px;
  padding: 10px 20px;
  font-size: 14px;
  cursor: pointer;
  transition: background-color 0.2s;
  font-weight: 500;
}

.refresh-btn:hover:not(:disabled) {
  background: #404040;
}

.refresh-btn:disabled {
  background: #ccc;
  cursor: not-allowed;
}

.footer-note {
  text-align: center;
  color: #B3B3B3;
  font-size: 14px;
  font-weight: 400;
  line-height: 21px;
  margin: 0;
}

/* Exam Cards Container */
.exam-cards-container {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 40px;
  width: 100%;
  margin-top: 20px;
}

/* Exam Card */
.exam-card {
  width: 100%;
  background: white;
  border-radius: 8px;
  border: 1px solid #D9D9D9;
  padding: 32px;
  box-sizing: border-box;
  min-height: 280px;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
}

.exam-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 32px;
}

.exam-left-info {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.exam-meta-item {
  display: flex;
  align-items: center;
  gap: 8px;
}

.meta-label {
  color: #B3B3B3;
  font-size: 12px;
  font-weight: 700;
  line-height: 18px;
  min-width: 49px;
}

.meta-badge {
  background: #E8EDF4;
  border-radius: 22369600px;
  padding: 1.5px 16px;
  color: black;
  font-size: 12px;
  font-weight: 700;
  line-height: 18px;
  text-align: center;
}

.exam-right-info {
  flex: 1;
  display: flex;
  justify-content: flex-end;
}

.exam-title-section {
  display: flex;
  align-items: flex-start;
  gap: 12px;
}

.exam-title {
  color: black;
  font-size: 24px;
  font-weight: 700;
  line-height: 28px;
  margin: 0;
}

.status-indicator {
  width: 8px;
  height: 8px;
  background: #10B981;
  border-radius: 50%;
  margin-top: 10px;
}

.exam-body {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 32px;
  padding-top: 20px;
  border-top: 0.67px solid #D9D9D9;
  flex-grow: 1;
}

.exam-details {
  display: flex;
  align-items: baseline;
  gap: 4px;
}

.details-label {
  color: #2C2C2C;
  font-size: 14px;
  font-weight: 700;
  line-height: 21px;
}

.details-text {
  color: black;
  font-size: 14px;
  font-weight: 700;
  line-height: 21px;
}

.exam-time-info {
  text-align: right;
}

.exam-time {
  color: #B3B3B3;
  font-size: 12px;
  font-weight: 700;
  line-height: 16px;
  margin-bottom: 8px;
}

.exam-duration {
  color: #B3B3B3;
  font-size: 12px;
  font-weight: 700;
  line-height: 16px;
}

.exam-actions {
  display: flex;
  gap: 24px;
  padding-top: 20px;
  border-top: 0.67px solid #F1F5F9;
}

.action-btn {
  flex: 1;
  height: 41px;
  background: #2C2C2C;
  border-radius: 8px;
  border: none;
  color: white;
  font-size: 14px;
  font-weight: 700;
  line-height: 21px;
  cursor: pointer;
  transition: background-color 0.2s;
}

.action-btn:hover {
  background: #404040;
}

.action-btn:active {
  background: #1a1a1a;
}

/* Loading, Error, Empty States */
.loading-container, .error-container, .empty-container {
  grid-column: 1 / -1;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 60px 20px;
}

.loading-spinner {
  width: 40px;
  height: 40px;
  border: 4px solid #f3f3f3;
  border-top: 4px solid #2C2C2C;
  border-radius: 50%;
  animation: spin 1s linear infinite;
  margin-bottom: 16px;
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

.loading-text, .error-text, .empty-text {
  color: #666;
  font-size: 16px;
  margin: 0;
}

.error-text {
  color: #e74c3c;
  margin-bottom: 16px;
}

.retry-btn {
  background: #2C2C2C;
  color: white;
  border: none;
  border-radius: 6px;
  padding: 8px 16px;
  font-size: 14px;
  cursor: pointer;
  transition: background-color 0.2s;
}

.retry-btn:hover {
  background: #404040;
}

/* 响应式设计 */
@media (max-width: 1300px) {
  .main-content {
    max-width: 95%;
  }
}

@media (max-width: 1024px) {
  .exam-cards-container {
    gap: 32px;
  }

  .main-content {
    padding: 32px 24px;
  }
}

@media (max-width: 768px) {
  .header {
    flex-direction: column;
    height: auto;
    padding: 16px;
    gap: 16px;
  }

  .navigation {
    gap: 32px;
  }

  .page-title {
    font-size: 32px;
    line-height: 48px;
  }

  .exam-cards-container {
    grid-template-columns: 1fr;
    gap: 24px;
  }

  .exam-card {
    padding: 24px;
    min-height: auto;
  }

  .exam-header {
    flex-direction: column;
    gap: 16px;
    margin-bottom: 20px;
  }

  .exam-right-info {
    justify-content: flex-start;
  }

  .exam-body {
    flex-direction: column;
    gap: 16px;
    margin-bottom: 20px;
  }

  .exam-time-info {
    text-align: left;
  }

  .exam-actions {
    flex-direction: column;
    gap: 16px;
  }

  .loading-container, .error-container, .empty-container {
    padding: 40px 20px;
  }

  .footer-section {
    margin-top: 32px;
    padding: 20px 16px;
  }
}
</style>